/*
* 文件：ColdUpdate.cs
* 作者：王阳
* 时间：2019-5-20
* 描述：
*/
//#define ENABLED
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;

namespace UnityX
{
#if ENABLED == false
    [System.Obsolete("软件冷更新服务系统功能未启用，请从UnityX窗口勾选：启用冷更新功能", false)]
#endif
    public class ColdUpdate
    {
        private static string serverIP = "127.0.0.1";
        private static int serverProt = 2022;
        private static string exclusionFiles = null;
        private static string cleanDirectorys = null;

        public static string versionFilePath { get { return Path.GetFullPath(Application.dataPath + "/ColdUpdate/Version.ini"); } }

        public static string CheckUpdate()
        {
            try
            {
                IPAddress[] iPAddresss = Dns.GetHostAddresses(serverIP);
                if (iPAddresss == null || iPAddresss.Length == 0)
                {
                    return null;
                }
                IPAddress iPAddress = iPAddresss[0];
                Socket m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                m_Socket.Connect(iPAddress, serverProt);
                if (m_Socket.Send(new byte[] { 33, 0, 2, 33 }) != 4)
                {
                    m_Socket.Close();
                    return null;
                }
                byte[] buffer = new byte[1024];

                int recvLength = 0;
                while (recvLength < 4)
                {
                    int len = m_Socket.Receive(buffer, recvLength, 4 - recvLength, SocketFlags.None);
                    if (len < 1)
                    {
                        m_Socket.Close();
                        return null;
                    }
                    recvLength += len;
                }
                int pakSize = BitConverter.ToInt32(buffer);
                recvLength = 0;
                while (recvLength < pakSize)
                {
                    int len = m_Socket.Receive(buffer, recvLength, pakSize - recvLength, SocketFlags.None);
                    if (len < 1)
                    {
                        m_Socket.Close();
                        return null;
                    }
                    recvLength += len;
                }
                string serverVersion = Encoding.UTF8.GetString(buffer, 0, pakSize);

                if (File.Exists(versionFilePath))
                {
                    string localVersion = File.ReadAllText(versionFilePath);
                    if (localVersion != serverVersion)
                    {
                        return serverVersion;
                    }
                }
                else
                {
                    return serverVersion;
                }
            }
            catch
            {
                return null;
            }
            return null;
        }
        public static void BootUpdate()
        {
            string tempDirectory = Application.temporaryCachePath + "/ColdUpdate";
            if (Directory.Exists(tempDirectory))
            {
                Directory.Delete(tempDirectory, true);
                Directory.CreateDirectory(tempDirectory);
            }
            else
            {
                Directory.CreateDirectory(tempDirectory);
            }
            File.Copy(Application.dataPath + "/ColdUpdate/b.exe", tempDirectory + "/b.exe", true);
            File.Copy(Application.dataPath + "/ColdUpdate/a.exe", tempDirectory + "/a.exe", true);

            string currentExePath = Path.GetFullPath(Application.dataPath.Replace("_Data", ".exe"));

            string exePath = Path.GetFullPath(tempDirectory + "/b.exe");
            string arguments = $"ip=\"{serverIP}\" port={serverProt} ud=\"{Directory.GetCurrentDirectory()}\" vf=\"{versionFilePath}\" sp=\"{currentExePath}\"";
            if (exclusionFiles != null && exclusionFiles.Length > 0)
            {
                string exclusionFile = "";
                string[] ss = exclusionFiles.Replace("[C]", Directory.GetCurrentDirectory()).Replace("[D]", Application.dataPath).Split(',');
                for (int i = 0; i < ss.Length; i++)
                {
                    exclusionFile += Path.GetFullPath(ss[i]) + ",";
                }
                arguments += $" ef=\"{exclusionFile}\"";
            }
            if (cleanDirectorys != null && cleanDirectorys.Length > 0)
            {
                string cleanDirectory = "";
                string[] ss = cleanDirectorys.Replace("[C]", Directory.GetCurrentDirectory()).Replace("[D]", Application.dataPath).Split(',');
                for (int i = 0; i < ss.Length; i++)
                {
                    cleanDirectory += Path.GetFullPath(ss[i]) + ",";
                }
                arguments += $" cd=\"{cleanDirectory}\"";
            }

            ProcessStartInfo processStartInfo = new ProcessStartInfo();
            processStartInfo.WorkingDirectory = Path.GetDirectoryName(exePath);
            processStartInfo.FileName = exePath;
            processStartInfo.Arguments = arguments;
            processStartInfo.UseShellExecute = false;
            Process.Start(processStartInfo);
        }
        public static void SkipVersion(string newVersion)
        {
            File.WriteAllText(versionFilePath, newVersion);
        }
    }
}